package com.itheima.health.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.health.dao.CheckGroupDao;
import com.itheima.health.dao.RoleDao;
import com.itheima.health.entity.PageResult;
import com.itheima.health.entity.QueryPageBean;
import com.itheima.health.pojo.CheckGroup;
import com.itheima.health.pojo.Role;
import com.itheima.health.service.CheckGroupService;
import com.itheima.health.service.RoleService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author zhangmeng
 * @description
 * @date 2019/9/18
 **/
@Service
@Slf4j
public class RoleServiceImpl implements RoleService {
    @Autowired
    private RoleDao roleDao;
    @Transactional
    @Override
    public void add(Role role, Integer[] permissionIds) {
        log.info("[角色-添加]data:{},permissionIds：{}", role, permissionIds);
        // 插入基本数据
        roleDao.insert(role);
        //逐条插入关系表数据
        for (Integer permissionId : permissionIds) {
            roleDao.insertRoleAndPermission(role.getId(),permissionId);
        }
    }

    @Override
    public PageResult pageQuery(QueryPageBean queryPageBean) {
        log.info("[角色-分页查询]data：{}",queryPageBean);
        //设置分页参数
        PageHelper.startPage(queryPageBean.getCurrentPage(),queryPageBean.getPageSize());
        //查询page
        Page<Role>  page= roleDao.selectByCondition(queryPageBean.getQueryString());
        //封装返回值
        return new PageResult(page.getTotal(),page.getResult());
    }

    @Override
    public Role findById(Integer id) {
        return roleDao.selectById(id);
    }

    @Override
    public List<Integer> findpermissionIdsByCheckRoleId(Integer id) {
        return roleDao.selectpermissionIdsByCheckRoleId(id);
    }

    @Override
    public void edit(Role  role, Integer[] permissionIds) {
        //1、更新检查组
        roleDao.update(role);
        //2、更新关联关系
        //2.1、删除原有关系
        roleDao.deleteRoleAndPermissionByPermissionId(role.getId());
        //2.2、加入当前关联关系
        for (Integer permissionId : permissionIds) {
            roleDao.insertRoleAndPermission(role.getId(),permissionId);
        }


    }

    @Override
    public List<Role> findAll() {
        //调用DAO查询数据并返回
        return roleDao.selectAll();
    }

    @Override
    public void delete(Integer id) {
        Role role = roleDao.selectById(id);
        roleDao.deleteRoleAndPermissionByPermissionId(role.getId());
        roleDao.deleteRoleById(id);

    }
}
